#!/bin/sh

# This script will be executed when PPP/WAN connection is established.

MODULE_NAME=transparentMode
MODULE_CFG=/opt/$MODULE_NAME/etc/settings

. $MODULE_CFG

# Outputs:
#  Print platform name (v1, v1i, v2i, v3, v4, v4i) if exists otherwise empty string is returned.
# Exit status:
#  Return 0 in any case
get_platform() {
  grep ICR_PLATFORM= /etc/os-release 2> /dev/null | sed s/ICR_PLATFORM=//
}

# The QuecOpen service on the SoM platforms reapplies its own network settings
# behind our back. The work-arounds guarded by som_platform below exist only
# for that and must not run on any other platform.
case "`get_platform`" in
  v1|v1i) som_platform=1 ;;
  *)      som_platform=0 ;;
esac

if [ "$MOD_TRANSPARENTMODE_ENABLED" = "1" ]; then
  # Zjistit pouzivany interface
  if [ $2 ]; then
    dev=$2
  else
    dev=`route -n | awk '$3 == "0.0.0.0" { print $8 }'`
  fi

  mkdir -p /run/transparentMode/
  echo "$dev" > /run/transparentMode/wan_interface

  if [ -x "/sbin/hash_generate" ]
  then
    dhcp_config_dir="/run/dhcp"
  else
    dhcp_config_dir="/var/dhcp"
  fi

  if [ "$som_platform" = 1 ] && [ -d "/run/dhcp" ]; then
    dhcp_config_dir="/run/dhcp"
  fi

  if [ -z $dev ]; then
    logger -t $MODULE_NAME "Mobile wan connection is not established."
    exit 1
  fi

  # Zapnuti proxy arp
  echo 1 > /proc/sys/net/ipv4/conf/eth0/proxy_arp
  echo 1 > /proc/sys/net/ipv4/conf/$dev/proxy_arp

  # Zjistit adresu SIM karty
  sim_ip=$1

  if [ -z $sim_ip ]; then
    logger -t $MODULE_NAME "Address of SIM card is not assigned."
    service ppp restart >/dev/null
    exit 1
  fi

  # Zjistit vychozi gateway
  export dev
  sim_gw=`route -n | awk '$3 == "0.0.0.0" && $8 == ENVIRON["dev"] { print $2 }' | head -n 1`
  if [ -z "$sim_gw" ]
  then
    sim_gw=`route -n | awk '$3 == "0.0.0.0" { print $2 }' | head -n 1`
  fi

  # Vypocteni nejmensi mozne site
  # 30, protoze nektere OS nepodporuji /31 masku
  mask=30
  while [ $mask -gt 0 ]
  do
    broadcast=$(ipcalc -sb $sim_ip/$mask | awk -F '=' '{print $2}')
    network=$(ipcalc -sn $sim_ip/$mask | awk -F '=' '{print $2}')

    [ "$sim_ip" != "$broadcast" ] && [ "$sim_ip" != "$network" ] && break

    mask=$(($mask - 1))
  done

  eth_netmask=$(ipcalc -sm $sim_ip/$mask | awk -F '=' '{print $2}')
  eth_network=$network

  logger -t $MODULE_NAME "Selected network $eth_network/$mask, broadcast $broadcast."

  ip_1=$(echo $sim_ip | awk -F '.' '{print $1}')
  ip_2=$(echo $sim_ip | awk -F '.' '{print $2}')
  ip_3=$(echo $sim_ip | awk -F '.' '{print $3}')
  ip_4=$(echo $sim_ip | awk -F '.' '{print $4}')

  network_4=$(echo $eth_network | awk -F '.' '{print $4}')

  # Rozhranni routeru bude mit ip adresu o jeden bit ruznou
  new_ip_4=$(($ip_4 - 1))
  if [ $new_ip_4 -eq $network_4 ]; then
    ip_4=$(($ip_4 + 1))
  else
    ip_4=$(($ip_4 - 1))
  fi

  eth_ip="$ip_1.$ip_2.$ip_3.$ip_4"

  logger -t $MODULE_NAME "eth0 ip is $eth_ip."

  dhcp_pool="range $sim_ip $sim_ip;"

  if [ "$som_platform" = 1 ]; then
    dns=$(awk '/^nameserver/ {if(s) s=s ", " $2; else s=$2} END {print s}' /etc/resolv.conf)
    if [ -n "$dns" ]; then
      dhcp_dns="\noption domain-name-servers $dns;"
    fi
  else
    dns=`cat /etc/resolv.conf | awk 'NR < 2{print $2}'`

    if [ $dns ]; then
      dhcp_dns="\noption domain-name-servers $dns;"
    fi
  fi

  # Nastaveni rozhranni
  ifconfig $dev 0.0.0.0 up

  # Toto zpusobi, ze min. 1 zarizeni pripojene ke stejnemu PPPoE serveru bude
  # nedostupne, ale lepsi reseni mne nenapada
  ifconfig eth0 $eth_ip netmask 255.255.255.255 up
  ifconfig eth0:0 192.168.1.1 netmask 255.255.255.0 up

  if [ "$som_platform" = 1 ]; then
    # Povoleni accept_local pre eth0 (New Addition)
    echo 1 > /proc/sys/net/ipv4/conf/eth0/accept_local

    # Nastaveni smerovani
    ip route del $sim_ip table local 2>/dev/null
    ip route replace $sim_ip dev eth0
  else
    # Nastaveni smerovani
    route add $sim_ip dev eth0
  fi
  route add $sim_gw dev $dev
  route add default gw $sim_gw dev $dev

  # Nastavit DHCP server na adresu SIM karty
  killall dhcpd
  rm /var/run/dhcpd.pid

  echo -e "option routers $eth_ip;" \
  "$dhcp_dns" \
  "\\ndefault-lease-time 60;" \
  "\\nmax-lease-time 86400;" \
  "\\nsubnet $eth_network netmask $eth_netmask { $dhcp_pool }" > $dhcp_config_dir/dhcpd.conf
  rm $dhcp_config_dir/dhcpd.leases
  touch $dhcp_config_dir/dhcpd.leases
  /usr/sbin/dhcpd -q -cf $dhcp_config_dir/dhcpd.conf -lf $dhcp_config_dir/dhcpd.leases eth0 2>/dev/null &

  # Prepise zdrojovou adresu veskereho provozu z routeru na IP adresu SIM karty
  service iptables restart
  iptables -t nat -I POSTROUTING -s $eth_ip -j SNAT --to $sim_ip

  # Static ARP
  arp -s $sim_gw ff:ff:ff:ff:ff:ff

  logger -t $MODULE_NAME "Transparent mode is running."

  exit 0
fi
